const express = require('express');
const router = express.Router();

//连接mysql数据库
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'yxb-blog'
});


router.post('/getArticle', (req, res) => {
  const { page=1, size=5, category } = req.body;

  const categorySql = category ? `where category="${category}"` : '';

  connection.connect();
  connection.query(`SELECT * from article ${categorySql} limit ${(page-1)*size},${size}`, function (error, results) {
    if (error) throw error;
    //利用map遍历删除返回数据中的文章内容
    results.map(item=>delete item.content);
    connection.query(`SELECT count(*) as length from article `,(err,len)=>{
      const length=Math.ceil(len[0].length/size);//计算总共有几页内容
      if (page>length) {
        res.send({code:-1,mes:'请求页数超过最大页数!'})
      }else{
        res.send({code:1,data:results,total:len[0].length})
      }
    })
  });
})

//修改文章信息接口
router.post('/alterAinfo',(req,res)=>{
  let {aid,type='read',num=1}=req.body;
  connection.connect();
  //出现一个bug,可以sql语句会执行两次,待解决
  connection.query("UPDATE article SET `"+type+"`=`"+type+"`+"+num+" WHERE aid="+aid, function (error, results) {
    if (error) throw error;
    res.send({code:1,mes:'修改成功'})
  });
})

//获取文章内容接口
router.post('/getContent',(req,res)=>{
  let {aid}=req.body;
  if (!aid) {
    res.send({code:-1,mes:'请求参数不能为空!'})
  }
  connection.connect();
  connection.query(`select content from article where aid="${aid}"`, function (error, results) {
    if (error) throw error;
    res.send({code:1,mes:'请求成功!', content:results[0].content})
  });

});

//搜索文章接口
router.post('/search',(req,res)=>{
  let {text}=req.body;
  if (!text) {
    res.send({code:-1,mes:'搜索内容不能为空!'})
  }
  connection.connect();
  //查找数据库中包含关键词的标题或内容
  connection.query(`SELECT * FROM article WHERE title LIKE '%${text}%' or content LIKE '%${text}%'`,function(error,results){
    if (error) throw error;
    res.send({code:1,data:results,total:results.length})
  })
})

module.exports = router;
